package com.lagou.task19;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReceiveTest {
    public static void main(String[] args) {
        DatagramSocket ds=null;
        try {
//        1创建DataGramSocket类型的对象并提供端口号
            ds = new DatagramSocket(8888);
//        2创建DataGramPacket类型的对象并提供缓冲区
            byte[] b1 = new  byte[20];
            DatagramPacket dp = new DatagramPacket(b1,b1.length);
//        3通过Socket接收数据存放到Packet里，调用 receive方法
            System.out.println("wait data...");
            ds.receive(dp);

            System.out.println("data : " + new String(b1,0,dp.getLength()));
//            /回消息
            byte[] ba1 = "收到消息".getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(ba1,ba1.length, dp.getAddress(),dp.getPort());
            ds.send(datagramPacket);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
//        4释放Socket并关闭有关的资源
    }
}
